import { createRouter, createWebHistory } from 'vue-router'

// 导入页面组件
import Layout from '@/views/Layout.vue'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Chat from '@/views/Chat.vue'
import Image from '@/views/Image.vue'
import Text from '@/views/Text.vue'
import Music from '@/views/Music.vue'
import Video from '@/views/Video.vue'
import Map from '@/views/Map.vue'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录 - CreativeAI Studio',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: Layout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'Home',
        component: Home,
        meta: {
          title: '首页 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      {
        path: '/chat',
        name: 'Chat',
        component: Chat,
        meta: {
          title: 'AI对话 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      // 预留其他AI功能路由
      {
        path: '/image',
        name: 'Image',
        component: () => import('@/views/Image.vue'),
        meta: {
          title: 'AI图像生成 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      {
        path: '/text',
        name: 'Text',
        component: () => import('@/views/Text.vue'),
        meta: {
          title: 'AI文本创作 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      {
        path: '/music',
        name: 'Music',
        component: () => import('@/views/Music.vue'),
        meta: {
          title: 'AI音乐创作 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      {
        path: '/video',
        name: 'Video',
        component: () => import('@/views/Video.vue'),
        meta: {
          title: 'AI视频制作 - CreativeAI Studio',
          requiresAuth: true
        }
      },
      {
        path: '/map',
        name: 'Map',
        component: () => import('@/views/Map.vue'),
        meta: {
          title: '地图探索 - CreativeAI Studio',
          requiresAuth: true
        }
      },
     
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('=== 路由守卫开始 ===')
  console.log('目标路径:', to.path)
  console.log('目标路由完整信息:', to)
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
    console.log('设置页面标题:', to.meta.title)
  }

  // 检查是否需要登录
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  console.log('是否需要认证:', requiresAuth)
  console.log('匹配的路由记录:', to.matched)
  
  if (requiresAuth) {
    console.log('需要认证，检查登录状态')
    
    // 检查本地存储的登录状态
    const isLoggedIn = localStorage.getItem('isLoggedIn')
    // 检查多种可能的用户信息存储键
    const userInfo = localStorage.getItem('user') || 
                   localStorage.getItem('userInfo') || 
                   localStorage.getItem('userData')
    
    console.log('本地存储登录状态:', isLoggedIn)
    console.log('本地存储用户信息:', userInfo)
    console.log('localStorage全部内容:', { ...localStorage })
    
    // 更严格的登录状态检查：既要有登录标志，也要有用户信息
    const hasValidLogin = isLoggedIn === 'true' && userInfo && userInfo !== 'null'
    console.log('是否有有效登录:', hasValidLogin)
    
    if (hasValidLogin) {
      try {
        // 尝试解析用户信息验证其有效性
        const user = JSON.parse(userInfo)
        if (user && (user.userId || user.id || user.username)) {
          console.log('用户已登录且信息有效，允许访问')
          next()
        } else {
          console.log('用户信息无效，清除登录状态')
          localStorage.removeItem('isLoggedIn')
          localStorage.removeItem('user')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('userData')
          redirectToLogin()
        }
      } catch (error) {
        console.log('用户信息解析失败，清除登录状态:', error)
        localStorage.removeItem('isLoggedIn')
        localStorage.removeItem('user')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('userData')
        redirectToLogin()
      }
    } else {
      console.log('用户未登录或登录状态无效，重定向到登录页面')
      redirectToLogin()
    }
    
    function redirectToLogin() {
      console.log('当前路径是否为登录页:', to.path === '/login')
      
      if (to.path !== '/login') {
        const redirectUrl = '/login?redirect=' + encodeURIComponent(to.fullPath)
        console.log('重定向到:', redirectUrl)
        next(redirectUrl)
      } else {
        console.log('已经是登录页，直接访问')
        next()
      }
    }
  } else {
    console.log('不需要认证的页面，直接访问')
    // 不需要认证的页面，直接访问
    next()
  }
  
  console.log('=== 路由守卫结束 ===')
})

export default router